<script setup lang="ts">
import { useFileDialog } from '@vueuse/core'
import type { ViewExcelProps } from './index.d'
import { fileDialogOption } from './index'
// ------------------use------------------
// #region
const props = withDefaults(defineProps<ViewExcelProps>(), {
  columns: () => Array.from({ length: 10 }).fill(0) as any[],
})
// import { pinyin } from 'pinyin-pro';
const pinyin: any = {}
const _xlsx: any = {
  read: {},
  utils: {},
  writeFile: {},
}
const { read, utils, writeFile } = _xlsx
const { vLoading, withLoading } = useDefineLoading()
const { open, onChange, reset } = useFileDialog(
  fileDialogOption,
)
onChange(handlerFileChange)
const [tableData, setTableData] = useState<any[]>([])
// #endregion
// ------------------静态变量------------------
// #region
// #endregion
// ------------------动态变量------------------
// #region

// #endregion
// ------------------ref-----------
// #region

// #endregion
// ------------------reactive------
// #region

// #endregion
// ------------------computed------
// #region
const handleData = computed(() =>
  tableData.value.length === 0
    ? Array.from({ length: 30 }).fill(0)
    : tableData.value,
)
const handleColumns = computed(() =>
  props.columns.length === 0
    ? Array.from({ length: 10 }).fill(0)
    : props.columns,
)
// #endregion
// ------------------生命周期------------------
// #region

// #endregion
// ------------------内置方法---------------------
// #region

// #endregion
// ------------------方法---------------------
// #region
function handlerFileChange(files: FileList | null) {
  if (!files)
    return
  try {
    // 读取表格
    const fileReader = new FileReader()
    fileReader.onload = (ev) => {
      const workbook = read(ev.target?.result, {
        type: 'binary',
      })
      const wsname = workbook.SheetNames[0]!
      const csv = utils.sheet_to_csv(
        workbook.Sheets[wsname]!,
      )
      withLoading(handlerTable)(csv.split('\n'))
      reset()
    }
    fileReader.readAsBinaryString(files[0]!)
  }
  catch (error) {}
}
async function handlerTable(data: string[]) {
  await sleep(1000)

  const tableHeader = data.shift()!.split(',')
  tableHeader.forEach((h, i) => {
    const o = handleColumns.value.find(
      (item: any) => item.title === h,
    ) as any
    if (!o)
      return
    o.$index = i
  })
  const arr: any[] = []
  data.forEach((str) => {
    const d = str.split(',')
    const o: Record<string, any> = {}
    handleColumns.value.forEach((c: any) => {
      !c.key
      && (c.key = pinyin(c.title, {
        toneType: 'none',
        type: 'array',
      }).join(''))
      o[c.key] = d[c.$index!] || ''
    })
    arr.push(o)
  })
  setTableData(arr)
  arr.forEach(item => handlerCellChange(item))
}
function handlerCellChange(row: Record<string, any>) {
  // const data = tableData.value[index];
  handleColumns.value.forEach((c: any) => {
    if (!c.onChange)
      return
    row[c.key!] = c.onChange?.(row, c)
    // console.log('进来了', key, row[key]);
  })
}
function download() {
  const o = handleColumns.value.filter(
    (item: any) => !item.onChange && item.key,
  )
  console.log(o, handleColumns.value, props.columns)
  const tableHeader = o.map((item: any) => item.title)
  const tableBody: any[] = []
  tableData.value.forEach((t) => {
    const arr: any[] = []
    o.forEach((item: any) => {
      arr[item.$index] = t[item.key]
    })
    tableBody.push(arr)
  })
  console.log('处理完成', [tableHeader, ...tableBody])

  // 创建 Workbook 对象
  const workbook = utils.book_new()

  // 创建 Worksheet 对象
  const worksheet = utils.json_to_sheet(tableBody, {
    header: tableHeader,
    skipHeader: true,
  })

  // 将 Worksheet 添加到 Workbook 中
  utils.book_append_sheet(workbook, worksheet, 'Sheet1')

  // 生成 Excel 文件并下载
  writeFile(workbook, 'data.xlsx')
}
// #endregion
defineExpose({
  open,
  download,
  getTableData: () => tableData.value,
  getColumns: () => handleColumns.value,
})
</script>

<template>
  <el-table
    v-loading
    border
    :data="handleData"
    class="height-fill view-excel"
  >
    <el-table-column type="index" label="#" />
    <el-table-column
      v-for="(item, i) in (handleColumns as any)"
      :key="i"
      :prop="item?.key || ''"
      :label="item?.title || String.fromCharCode(65 + i)"
    >
      <template #default="{ row }">
        <component
          :is="item.render"
          v-if="item.render"
          v-model="row[item.key]"
          :disabled="!row || !!item.onChange"
          placeholder=""
          :title="!!item.onChange ? '该值为自动计算！' : ''"
          @change="handlerCellChange(row)"
        />
        <el-input
          v-else
          v-model="row[item.key]"
          :disabled="!row || !!item.onChange"
          placeholder=""
          :title="!!item.onChange ? '该值为自动计算！' : ''"
          @input="handlerCellChange(row)"
        />
      </template>
    </el-table-column>
  </el-table>
</template>

<style lang="scss">
.view-excel {
  --el-table-header-bg-color: var(--el-bg-color-page);
  .el-table__body {
    .el-table__cell {
      cursor: cell;
      position: relative;
      &::before {
        cursor: cell;
        opacity: 0;
        transition: all 0.2s var(--motion-bezier);
        content: '';
        position: absolute;
        top: 0px;
        left: 0px;
        z-index: 9;
        width: 100%;
        height: 100%;
        outline: 1px solid var(--el-text-color-disabled);
        outline-offset: -2px;
        // background-color: red;
        box-sizing: border-box;
        pointer-events: none;
      }
    }
    .el-table__cell:focus-within {
      background-color: red;
    }
    .el-table__cell[class]:not(
        .el-table_1_column_1
      ):hover::before {
      opacity: 0.8;
    }
    .el-table__cell[class]:not(
        .el-table_1_column_1
      ):focus-within::before {
      opacity: 1;
    }
  }
  .cell {
    text-align: center;
    cursor: cell;
  }

  .cell > .el-input[class] {
    width: 100% !important;
    height: 100% !important;
    .el-input__wrapper {
      box-shadow: none;
      background-color: transparent;
      cursor: cell;
      outline: none;
    }
    input {
      cursor: cell;
    }
  }
  .el-input[class].is-disabled {
    cursor: not-allowed;
    .el-input__wrapper[class],
    input[class] {
      cursor: not-allowed;
    }
  }
}
//------------------组件样式------------------
//-------------样式穿透-------------
</style>

<style lang="scss" scoped>
//------------------组件样式------------------
//-------------样式穿透-------------
</style>
